package com.my.app.tools.util;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public enum AppThreadUtil {

    //
    INSTANCE;

    AppThreadUtil() {
        executor = new AppPoolExecutor();
    }

    private ThreadPoolExecutor executor;

    public ThreadPoolExecutor getExecutor() {
        return executor;
    }
}

class AppPoolExecutor extends ThreadPoolExecutor {

    private static final int CORE_POOL_SIZE = 20;
    private static final int MAXIMUM_POOL_SIZE = 50;
    private static final long KEEP_ALIVE_TIME = 60;
    private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;

    public AppPoolExecutor() {
        super(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT,
                new LinkedBlockingQueue<Runnable>(100), new ThreadPoolExecutor.CallerRunsPolicy());
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        LogUtil.info(r.toString() + " | begin.");
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {//线程执行结束时
        super.afterExecute(r, t);
        if (t != null) {
            LogUtil.error(r.toString() + " | error. | " + t.getMessage());
        } else {
            LogUtil.info(r.toString() + " | finish.");
        }
    }

}
